angular.module("app").component("winitPrototype", {
    templateUrl: getTemplateUrl("matrix/component/tpl/winitPrototype.html"),
    bindings: {
        reqId          : "<",   
        featureId      : "<",
        panelType      : "@",   //功能树：tree
        selectedBranch : '=',   //功能树选择的节点数据
        showType       : '<',   //是否显示类型按钮组  显示：true
        showPattern    : '<',   //是否显示模式按钮组  显示：true
        isReadonly     : '<',   //是否只读           只读：true



        sys       : "=",
        readonly: "<",
        mid     : '<',
        featureIndex: '@',
        prevData        : "<",    //比较数据一
        nextData        : "<"     //比较数据二
    },
    controller: function ($scope, $rootScope, $stateParams, $http, $timeout, lodash) {
        var self = this;
        // new  *************************************************************
        $scope.info = {
            defaultPrototypeType: "prototype",   //默认选中贴图
            //类型单选按钮组数据   
            prototypeTypeList: [
                {"type": "prototype",  "name": "贴图"},
                {"type": "axure",      "name": "Axure"},
                {"type": "expression", "name": "表达式"}
            ], 
            defaultPrototypePattern: "current",   //默认选中当前
            //模式单选按钮组数据 
            prototypePatternList: [
                {"type": "current", "name": "当前"},
                {"type": "online",  "name": "线上"},
                {"type": "compare", "name": "对比"},
            ],
            isRelation    : false,   //未关联: true
            isConfict     : false,   //冲突: true
            reqDetails    : "",      //req时的全部数据
            masterDetails : "",      //master时的全部数据
            prototypePath : "",      //原型数据路径
            reqConfictName: "",      //记录导致版本冲突的需求名称
            reqOriginData : "",      //记录req的prototype数据，用于保存时判断
        }

        //确保每次都能取到更新的值
        self.$onChanges = function(data) {
            if(self.panelType == "tree") {
                // 功能点页面
                isExistFeature($stateParams.reqId, self.featureId);
                $timeout(function() {
                    if($scope.info.masterDetails.attr && $scope.info.reqDetails.attr && !$scope.info.isRelation) {
                        $scope.info.isConfict = $scope.info.masterDetails.attr.version != $scope.info.reqDetails.attr.master_version ? true : false;
                        $scope.info.reqConfictName = $scope.info.masterDetails.attr.req_snapshot;
                    }
                }, 1000);
            } else {
    
            }
        }

        // 检查当前req是否已经被关联（只有在有功能树的页面才需要调用此方法）
        function isExistFeature(reqId, featureId) {
            var url = matrix_product_url +"/feature/getAllFeatureForReq?reqId="+ reqId;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    var isExistIndex = lodash.findIndex(result.data, function(res) {
                        return res.id == featureId;
                    });
                    if(isExistIndex == -1) {
                        getPrototypeDetails("-1", featureId);
                    } else {
                        // 在已经被关联的时候，需要多请求一次master数据，用于判断是否版本冲突
                        getPrototypeDetails("-1", featureId);
                        getPrototypeDetails(reqId, featureId);
                    }
                    $scope.info.isRelation = isExistIndex == -1 ? true : false;
                } else {
                    $rootScope.toasterErrorInfo("获取当前需求关联列表失败！");
                }
            });
        }

        // 获取req原型数据
        function getPrototypeDetails(reqId, featureId, pattern) {
            console.log(reqId != "-1" ? "req请求" : "master请求");
            var url = matrix_product_url +"/feature/getFeature?id="+ featureId +"&reqId="+ reqId +"&withPrototype=1&withAttr=1";
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    reqId != "-1" ? $scope.info.reqDetails = result.data[0] : $scope.info.masterDetails = result.data[0];
                    $scope.info.prototypePath = result.data[0].path +"/"+ result.data[0].featureName;
                    // 用于修改数据时的比较判断
                    if(reqId != "-1") {
                        $scope.info.reqOriginData = result.data[0].attr ? angular.copy(result.data[0].attr) : "";
                    }
                    // 判断要加载的Axure
                    if(pattern != "online") {
                        setIframe($scope.info.reqDetails.attr.prototype_file_path, featureId);
                    }
                    if(pattern != "current") {
                        setIframe($scope.info.masterDetails.attr.prototype_file_path, featureId);
                    }
                } else {
                    $rootScope.toasterErrorInfo("获取原型数据失败！");
                }
            });
        }

        // 选择类型(贴图，Axure，表达式)
        $scope.clickPrototypeType = function(type) {
            if(type.type == "axure") {
                if($scope.info.reqDetails.attr.prototype_file_path) {
                    setIframe($scope.info.reqDetails.attr.prototype_file_path, self.featureId);
                }
            }
        };

        // 选择模式(当前，线上，对比)
        $scope.clickPrototypePattern = function(pattern) {
            $scope.info.defaultPrototypePattern = pattern.type;
            switch(pattern.type) {
                case "current":
                    var reqId = self.panelType == "tree" ? $stateParams.reqId : self.reqId;
                    getPrototypeDetails(reqId, self.featureId, "current");
                    break;
                case "online":
                    getPrototypeDetails("-1", self.featureId, "online");
                    break;
                case "compare":
                    var reqId = self.panelType == "tree" ? $stateParams.reqId : self.reqId;
                    getPrototypeDetails(reqId, self.featureId);
                    getPrototypeDetails("-1", self.featureId, "compare");
                    break;
            }
        };

        // 失焦保存数据
        $scope.saveBlurPrototype = function(value) {
            // 失焦保存的时候，保存原型数据只需要比较attr.prototype即可
            if(!lodash.isEqual(value, $scope.info.reqOriginData.prototype)) {
                savePrototypeData(value);
            }
        };

        // 保存数据
        function savePrototypeData(value) {
            var reqId = self.panelType == "tree" ? $stateParams.reqId : self.reqId;
            // req
            var postParams = {
                id    : self.featureId,
                attr  : {
                    prototype: value
                },
                reqId : reqId
            };
            // master
            var masterPostparams = {
                id: self.featureId,
                attr: {
                    prototype: value
                },
                featureName: "页面"
            };
            var url = matrix_product_url +"/feature/"+ ($stateParams.reqId == "-1" ? "updateFeature" : "updateFeatureAttrForReq");
            $http({
                method: "post",
                url: url,
                data: JSON.stringify($stateParams.reqId == "-1" ? masterPostparams : postParams),
                headers: {"Content-Type": "application/json"}
            }).success(function (result) {
                if (result.code == "0") {
                    $scope.info.reqOriginData = angular.copy($stateParams.reqId == "-1" ? masterPostparams.attr : postParams.attr);
                    $scope.$emit('getFeaturesByReq', '');
                    $rootScope.toasterSuccessInfo("数据修改成功！");
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        };

        // 解决冲突
        $scope.fixConfict = function() {
            var confirmParams = {
                "titleData": "提示",
                "bodyData": "确定要解决冲突吗？"
            };
            $rootScope.confirmWindow(confirmParams, function (data) {
                if(data) {
                    var attrData = $scope.info.reqDetails.attr;
                    attrData.master_version = $scope.info.masterDetails.attr.version;
                    attrData.req_snapshot   = $scope.info.masterDetails.attr.req_snapshot;
                    var postParams = {
                        id    : self.featureId,
                        attr  : attrData,
                        reqId : $stateParams.reqId
                    };
                    var url = matrix_product_url + "/feature/updateFeatureAttrForReq";
                    $http({
                        method: "post",
                        url: url,
                        data: JSON.stringify(postParams),
                        headers: {"Content-Type": "application/json"}
                    }).success(function (result) {
                        if (result.code == "0") {
                            $rootScope.toasterSuccessInfo("解决冲突成功！");
                            $scope.info.isConfict = false;
                        } else {
                            $rootScope.toasterErrorInfo(result.desc);
                        }
                    });
                }
            });
        };

        // 调用mFunTree.js中的修改方法进行关联操作
        $scope.$on('editFeature', function (event, data) {
            relationFeature();
        });

        // 关联原型
        function relationFeature() {
            var url = matrix_product_url +"/feature/featureOccupy?reqId="+ $stateParams.reqId +"&id="+ self.selectedBranch.id;
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    isExistFeature($stateParams.reqId, self.selectedBranch.id);
                    $rootScope.toasterSuccessInfo("关联成功！");
                } else {
                    $rootScope.toasterErrorInfo("关联功能点失败，请刷新重试！");
                }
            });
        };

        // 上传Axure
        $("#uploadfile").fileinput({
            language: 'zh',       // 设置语言
            uploadUrl: matrix_product_url + '/feature/uploadPrototypeFile',
            showPreview: false,   // 是否显示预览
            allowedFileExtensions: ["zip"],
            uploadAsync: false,
            uploadExtraData: function () {
                var postParams = {
                    reqId      : $stateParams.reqId ? $stateParams.reqId : self.reqId,
                    featureId  : self.featureId,
                    patternType: "axure"
                };
                return postParams;
            }
        }).on("filebatchuploadsuccess", function (event, data) {
            if (data.response.code == "0") {
                document.getElementById("errorMessageOfType").style.display  = "none";
                document.getElementById("errorMessageOfValue").style.display = "none";
                var crtReqId = $stateParams.reqId ? $stateParams.reqId : self.reqId;
                if(crtReqId == "-1") {
                    $scope.info.masterDetails.attr.prototype_file_path = data.response.data;
                } else {
                    $scope.info.reqDetails.attr.prototype_file_path = data.response.data;
                }
                $("#iframepage").remove();
                setIframe(data.response.data, self.featureId);
            } else {
                document.getElementById("errorMessageOfType").style.display = $(".file-caption-name").html() == "" ? "none" : "inline-block";
                return false;
            }
        }).on('fileerror', function (event, data, msg) {  //一个文件上传失败
            console.log('文件上传失败！' + msg);
        });

        $(".fileinput-upload-button").on("click", function() {
            document.getElementById("errorMessageOfType").style.display = "none";
            if($(".file-caption-name").html() == "") {
                document.getElementById("errorMessageOfValue").style.display = "inline-block";
                return false;
            }
        });

        $(".fileinput-remove-button").on("click", function() {
            document.getElementById("errorMessageOfType").style.display  = "none";
            document.getElementById("errorMessageOfValue").style.display = "none";
        });

        // 设置iframe
        function setIframe(ifram_path, featureId, masterId) {
            $("#"+ featureId +"iframepage").remove();
            $("#iframepage").remove();
            var iframeId = featureId ? (featureId + "iframepage") : "iframepage";
            $(".down-file-btn").css("display", "block");
            $(".mm-loading-icon").css("display", "block");
            var url = axure_prototype_url + ifram_path + "index.html?time="+ new Date();
            var iframe = $("<iframe id='"+iframeId+"' class='iframClass' frameborder='0' scrolling='auto' marginheight='0' marginwidth='0' style='width: 100%;height:100%;transform: scale(" + $scope.scale + ");transform-origin: 0 0;'>");
            iframe.attr('src', url);
            iframe.load(function () {
                $(".mm-loading-icon").css("display", "none");
            });

            if(masterId) {
                $("#"+ featureId +"iframepage").remove();
                $(masterId).append(iframe);
            } else {
                var reqIframeId = featureId ? featureId + "col-iframe" : "col-iframe";
                $timeout(function() {
                    $("#"+ featureId +"iframepage").remove();
                    $('#'+ reqIframeId).append(iframe);
                }, 500);
            }
        };      

        // 放大
        $scope.iframePlus = function () {
            if ($scope.scale < 1) {
                $scope.scale += 0.1;
                $("#iframepage").css("transform", "scale(" + $scope.scale + ")");
            }
        };

        // 缩小
        $scope.iframeMinus = function () {
            if ($scope.scale > 0.1) {
                $scope.scale -= 0.1;
                $("#iframepage").css("transform", "scale(" + $scope.scale + ")");
            }

        };

        // 下载
        $scope.downFile = function() {
            var url = matrix_product_url +"/feature/getPrototypeFile?reqId="+ $stateParams.reqId +"&featureId="+ self.selectedBranch.id;
            window.location.href = url;
        };
    }
});